package cn.wolfcode.rbac.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Getter
@Setter
public class JwtUtils {

    @Value("${jwt.secret}")
    public String secret;
    @Value("${jwt.header}")
    private String header;

    /**
     * 根据单个payload创建token
     * @param key payload的key
     * @param value payload的value
     * @return token
     */
    public String createToken(String key,String value){
        return JWT.create().withClaim(key, value).sign(Algorithm.HMAC256(secret));
    }

    /**
     * 根据map的payload创建token
     * @param payloads map集合封装多个payload
     * @return token
     */
    public String createToken(Map<String,String> payloads){
        JWTCreator.Builder builder = JWT.create();
        payloads.forEach((key,value)->builder.withClaim(key,value));
        String token = builder.sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 通过解析token，根据name获取payload
     * @param token 解析的token
     * @param name  获取payload的属性名
     * @return payload的值
     */
    public String getPayload(String token,String name){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        String payload = decodedJWT.getClaim(name).asString();
        return payload;
    }
}
